package com.nti56.springboot.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nti56.springboot.model.PageResponse;
import com.nti56.springboot.model.User;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.NumberUtil;
import com.nti56.springboot.utils.StringUtil;

public abstract class BaseController 
{

	protected Map<String, String> getParamMap(HttpServletRequest request){
		return getParamMap(request, true);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Map<String, String> getParamMap(HttpServletRequest request, boolean includePagParams) {
		Map<String,String> paramMap = new HashMap<String,String>();
		try {
			Enumeration<?> paramNames = request.getParameterNames();
			while(paramNames.hasMoreElements()){
				String paramName = URLDecoder.decode(paramNames.nextElement().toString(), "UTF-8");
				String originalParamValue = request.getParameter(paramName);
				if(!StringUtil.isEmpty(originalParamValue)){
					//url中含有普通的%字符的情况，如果直接用URLDecode.decode()则会出现如题的错误
					originalParamValue = originalParamValue.replaceAll("%", "%25");
				}
				String paramValue = URLDecoder.decode(originalParamValue, "UTF-8");
				paramMap.put(paramName, paramValue);
			}
			
		} catch (UnsupportedEncodingException e) {
			//logger.error(e.getStackTrace());
		}
		Map<String, String> map = this.escapeChar(paramMap);
		return map;
	}
	
	/**
	  * 排序参数不转义
	 * @param paramMap
	 * @return
	 */
	private Map<String,String> escapeChar(Map<String,String> paramMap){
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			if(!"sort".equals(entry.getKey())) {
				String escapeValue = escapeChar(entry.getValue());
				entry.setValue(escapeValue);
			}
		}
		return paramMap;
	}
	
	/**
	 *    转义 字符
	 * @param before
	 * @return
	 */
	private String escapeChar(String before) {
		if (!StringUtil.isEmpty(before)) {
			//before = before.replaceAll("/", "//");
			//before = before.replaceAll("_", "/_");
			//before = before.replaceAll("%", "/%");
			before = before.replaceAll("'", "''");
		}
		return before;
	}
 
	/**
	 * 使用分页插件
	 * @param request
	 */
	protected void startPage(HttpServletRequest request) {
		Map<String, String> paramMap = this.getParamMap(request);
		String page = paramMap.get("page");
		String rows = paramMap.get("rows");
		String sort = paramMap.get("sort");
		String order = paramMap.get("order");		
		String orderBy = this.getOrderBy(sort, order);
		if(!StringUtil.isEmpty(page) && !StringUtil.isEmpty(rows))
		{			
			Integer pageNum = NumberUtil.toInteger(paramMap.get("page"));
			Integer pageSize = NumberUtil.toInteger(paramMap.get("rows"));
			if(StringUtil.isEmpty(orderBy)) {
				PageHelper.startPage(pageNum, pageSize);
			}else {
				PageHelper.startPage(pageNum, pageSize,orderBy);
			}
		}		
	}
	
	/**
	   *  支持多列排序
	 *  sortName:'carrier_code,is_short,start_miles,end_miles',
	    sortOrder:'desc,desc',
	 * @param sort 排序字段      
	 * @param order 排序方式
	 * @return
	 */
	private String getOrderBy(String sort,String order) {
		if(StringUtil.isEmpty(sort)) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		String orderBy = "";
		if(!sort.contains(",")) {	
			sb.append(sort);
			if(!StringUtil.isEmpty(order)) {
				sb.append(" "+order);
			}
			orderBy = sb.toString();
			return orderBy;
		}else {
			String[] sortAry = sort.split(",");
			String[] orderAry = order.split(",");
			if(sortAry.length == orderAry.length) {
				for(int i=0;i<sortAry.length;i++) {
					sb.append(sortAry[i] +" "+orderAry[i]+",");
				}
			}else {
				for(int j=0;j<sortAry.length;j++) {
					if(j<orderAry.length) {
						sb.append(sortAry[j] +" "+orderAry[j]+",");
					}else {
						sb.append(sortAry[j] +",");
					}
				}
			}
			orderBy = sb.toString();
			orderBy = orderBy.substring(0, orderBy.length() - 1);
			return orderBy;
		}
	}
	
	protected PageResponse getPageResponse(List list){
		PageResponse  pageResponse = new PageResponse();
		PageInfo pageInfo = new PageInfo(list);
		long total = pageInfo.getTotal();
		pageResponse.setTotal(total);
		pageResponse.setRows(list);
		pageResponse.setFlag(true);
		pageResponse.setResultCode(Constant.RES_SUCCESS);
		pageResponse.setMsg("查询成功!");
		return pageResponse;		
	}
	
	protected PageResponse getErrorPageResponse(Exception e){
		PageResponse  pageResponse = new PageResponse();
		pageResponse.setTotal(0);
		pageResponse.setRows(null);
		pageResponse.setFlag(true);
		pageResponse.setResultCode(Constant.RES_FAILED);
		pageResponse.setMsg("查询失败!");
		return pageResponse;		
	}
	
	protected User getLoginUser(){
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
		if(attrs != null)
		{
			HttpServletRequest request = attrs.getRequest();
			if(request != null)
			{
				HttpSession session = request.getSession();
				return (User)session.getAttribute(Constant.SESSION_USER_KEY);
			}
		}
		return null;
	}
}
